package com.dins.elashutina.parser;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: ekaterina.lashutina
 * Date: 04.09.13
 * Time: 15:12
 */
public class BullsEyeParser {

    static String path="";

    public static Tree startBullsEyeParser(File fileName, Tree tree) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(fileName));
            String line;
            while ((line = reader.readLine()) != null) {
                bullsEyeParse(line, tree);
            }
            return tree;
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Exception");
            e.printStackTrace();
        }
        return tree;
    }

    public static void bullsEyeParse(String line,Tree tree) {
        if (line.startsWith("<folder") || line.startsWith("<src") || line.startsWith("<fn")) {
            String[] tmp = line.split("\"");
            String newpath = "";
            newpath += "\\" + tmp[1];
            List<String> args = new ArrayList<String>();
            if (line.startsWith("<src")) {
                args.add(tmp[5]);
                args.add(tmp[7]);
                args.add(tmp[9]);
                args.add(tmp[11]);
                args.add(tmp[13]);
                args.add(tmp[15]);
            } else {
                args.add(tmp[3]);
                args.add(tmp[5]);
                args.add(tmp[7]);
                args.add(tmp[9]);
                args.add(tmp[11]);
                args.add(tmp[13]);
            }
            if (tree.isEmpty()) {
                tree.setRoot(new Node(newpath, path + newpath, args, null));
            } else {
                String s = path;
                Node n = tree.getNode(path);
                 tree.add(new Node(newpath, path + newpath, args, tree.getNode(path)));
            }
            path += newpath;
        } else if (line.startsWith("</folder") || line.startsWith("</src") || line.startsWith("</fn")) {
            //
            String[] tmp = path.split("\\\\");
            path = "";
            for (int i = 1; i < tmp.length - 1; i++) {
                path += "\\"+tmp[i];
            }
        } else return;
    }
}
